<template>
  <div class="card-setting-container">
    <!-- start 附加组件设置头部 -->
    <div class="card-setting-header">
      <div class="card-setting-title">
        <h2>{{$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.title1')}}</h2>
        <el-button type="primary" @click="onClickCreateHandler">
          <i class="iconfont icon-add2"></i>
          {{$t('common.base.add2')}}
        </el-button>
      </div>
      <div class="card-setting-msg">
        {{$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.tips1')}}
        <el-tooltip placement="top" popper-class="card-display-tooltip">
          <div slot="content">
            <template>
              <div class="card-displaymode-item">● {{$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.tips2')}}</div>
              <div class="card-displaymode-item">● {{$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.tips3')}}</div>
            </template>
          </div>
          <i class="iconfont icon-question"></i>
        </el-tooltip>
      </div>
    </div>
    <!-- end 附加组件设置头部 -->

    <!-- start 附加组件列表 -->
    <div class="card-setting-list" v-if="additionalComponentList.length">
      <draggable
        v-model="additionalComponentList"
        v-bind="{ animation: 380, ghostClass: 'ghost' }"
        tag="div"
        class="card-group"
        @change="handleUpdateCardOrder"
      >
        <card-item
          class="card-item"
          v-for="(card, idx) in additionalComponentList"
          :key="card.id"
          :index="idx"
          :event-card="card"
          @deleteCard="deleteCard"
          @showPreview="onShowPreviewCardDialog"
          @showEditRule="onShowEditRuleDialog"
          @showEditPremiss="onShowEditPremissDialog"
          @edit="onEditConnectorCardHandler"
          @update="updateEventDataHandler"
        ></card-item>
      </draggable>
    </div>
    <!-- end 附加组件列表 -->

    <!-- start 无数据 -->
    <no-data-view-new
      v-else
      :notice-msg="$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.tips4')"
    ></no-data-view-new>
    <!-- end 无数据 -->

    <!-- start 添加附加组件弹窗 -->
    <add-card-dialog
      :event-card-list="additionalComponentList"
      :visiable.sync="isShowAddCardModal"
      :card-sys-list="cardSysList"
      @update="update"
      @updateImport="updateImport"
    ></add-card-dialog>
    <!-- end 添加附加组件弹窗 -->

    <!-- start 规则设置弹窗 -->
    <edit-rules-dialog
      :event-card="currentCard"
      :visiable.sync="editRulesDialogVisiable"
    ></edit-rules-dialog>
    <!-- end 规则设置弹窗 -->

    <!-- start 权限设置弹窗 -->
    <edit-premiss-dialog
      :event-card="currentCard"
      :visiable.sync="editPremissDialogVisiable"
      :role-list="roleList"
    ></edit-premiss-dialog>
    <!-- end 权限设置弹窗 -->

    <!-- start 预览附加组件弹窗 -->
    <preview-card-dialog
      ref="previewCardRef"
      :fields="previewFields"
    ></preview-card-dialog>
    <!-- end 预览附加组件弹窗 -->
    
    <!-- start 新建附加组件或连接器弹窗 -->
    <ConnectorModuleAddCardDialog
      :visible="isShowNewCreateCardModal"
      @cardCreate="onCardCreateHandler"
      @connectorCreate="onConnectorCreateHandler"
      @close="onCloseNewCreateCardModal"
    />
    <!-- end 新建附加组件或连接器弹窗 -->
    
    <!-- start 连接器新建弹窗 -->
    <ConnectorModuleCreateConnectorDialog
      v-if="serviceEventTypeId"
      :title="connectorCreateModalTitle"
      :visible="isShowCreateConnectorModal"
      :bizTypeId="bizTypeId"
      :toBizType="toBizType"
      :fromBizType="fromBizType"
      :fromBizTypeName="fromBizTypeName"
      isShowSelectLanguage
      @close="onCloseCreateConnectorModal"
      @finish="updateEventDataHandler"
    />
    <!-- end 连接器新建弹窗 -->
    
    <!-- start 编辑连接器弹窗 -->
    <ConnectorModuleEditConnectorDialog
      :title="connectorEditModalTitle" 
      :fromBizTypeName="fromBizTypeName"
      :visible="isShowEditConnectorModal"
      :connectorInfo="connectorInfo"
      @close="onCloseEditConnectorModal"
      @finish="updateEventDataHandler"
    />
    <!-- end 编辑连接器弹窗 -->
    
  </div>
</template>

<script>
/* component */
import draggable from 'vuedraggable';
import CardItem from '../components/CardItem.vue';
import AddCardDialog from '../components/AddCardDialog.vue';
import EditRulesDialog from '../components/EditRulesDialog.vue';
import EditPremissDialog from '../components/EditPremissDialog.vue';
import PreviewCardDialog from '../../../additional/components/PreviewCardDialog.vue';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
/* api */
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';
/* util */
import { isBasicEditionControl } from '@shb-lib/version';
import { cloneDeep } from 'lodash';
/* constant */
import { ADDITIONAL_TYPE_MAP } from '../../../constant';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* mixin */
import { ConnectorModuleCardSettingEventMixin } from '@src/modules/connector'
/* service */
import { isConnectorCard } from '@service/CardService';

export default {
  name: 'card-setting-panel',
  inject: ['flowData'],
  mixins: [ConnectorModuleCardSettingEventMixin],
  props: {
    eventTypeName: {
      type: String,
      default: '',
    },
    serviceEventTypeId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      previewFields: [], //  预览组件的字段
      currentCard: {}, //  当前操作的附加组件
      editPremissDialogVisiable: false, //  编辑权限弹窗展示(隐藏)
      editRulesDialogVisiable: false, // 编辑规则弹窗展示(隐藏)
      roleList: [], // 角色列表
      cardSysList: [], // 模板库列表
      authInfo: [],
      cloneOldCard: [],
    };
  },
  computed: {
    isBasicEditionControl() {
      return isBasicEditionControl();
    },
    serviceEventTypeConfig() {
      return this.flowData?.serviceEventTypeConfig || {};
    },
    nameAndColor() {
      return {
        name: this.serviceEventTypeConfig.name,
        color: this.serviceEventTypeConfig.config.color
      }
    },
    additionalComponentList: {
      get() {
        return this.serviceEventTypeConfig?.cardSetting?.cardInfo || [];
      },
      set(value) {
        this.$set(this.flowData.serviceEventTypeConfig.cardSetting, 'cardInfo', value);
      }
    },
  },
  methods: {
    /* 查询附加组件字段信息 */
    fetchCardFields(card) {
      SettingServiceEventApi.getCardFieldList({ cardId: card.id, isFromSetting: false })
        .then(res => {
          this.previewFields = res || [];
        })
        .catch(err => console.error(err))
    },
    /* 查询角色列表 */
    fetchRoleList() {
      SettingServiceEventApi.getRoleList({ pageSize: 0 })
        .then(res => {
          const { list = [] } = res;

          if (this.isBasicEditionControl) {
            this.roleList = list.filter(item => item.id !== '6' && item.id !== '7' && item.id !== '8' && item.id !== '10');
          } else {
            this.roleList = list;
          }

          // 新组件默认权限
          this.authInfo = this.roleList.map(role => {
            return {
              id: role.id,
              name: role.name,
              canRead: true,
              canWrite: true,
              canCreate: true,
              canDelete: true
            }
          })
        })
    },
    /* 查询模板库列表 */
    fetchTemplateLibraryList() {
      SettingServiceEventApi.getSystemTemplateList({ id: 1 })
        .then(res => {
          const { status, message, data = [] } = res;

          if (status == 0) {
            // TODO-bdz 中文判断
            this.cardSysList = data.filter(card => card.cardName !== '工时记录')
              .map(item => {
                return {
                  ...item,
                  type: ADDITIONAL_TYPE_MAP[item.cardId],
                };
              });
          } else {
            this.$message.error(message);
          }
        })
        .catch(err => console.error(err))
    },
    /* 更新附加组件排序 */
    handleUpdateCardOrder() {
      this.additionalComponentList.forEach((item, idx) => {
        item.order = idx + 1;
      })
    },
    /* 删除附加组件 */
    deleteCard(index) {
      this.additionalComponentList.splice(index, 1);
      this.$platform.notification({
        title: this.$t('common.base.tip.deleteSuccess'),
        type: 'success'
      });
    },
    /* 显示附加组件预览弹窗 */
    onShowPreviewCardDialog(card) {
      this.previewFields = [];
      this.fetchCardFields(card);
      this.$refs.previewCardRef.openDialog();
    },
    /* 显示权限设置弹窗 */
    onShowEditPremissDialog(eventCard) {
      this.currentCard = eventCard;
      this.editPremissDialogVisiable = true;
    },
    /* 显示规则设置弹窗 */
    onShowEditRuleDialog(eventCard) {
      this.currentCard = eventCard;
      this.editRulesDialogVisiable = true;
    },
    /* 从已添加的组件库添加 */
    update(checked) {
      // 取原先已添加的组件（交集）
      let originChecked = this.additionalComponentList.filter(item => {
        // 连接器附加组件
        if (isConnectorCard(item)) return true
        return checked.some(card => card.id === item.id)
      });
      // 取新添加的组件（差集）
      let newChecked = checked.filter(item => originChecked.every(card => card.id !== item.id));

      // 格式化新添加的组件数据
      newChecked.forEach(card => {
        card.notNullFlow = [];
        card.stateCanEdit = null;
        card.authInfo = this.authInfo;
      })

      this.additionalComponentList = originChecked.concat(newChecked);
    },
    /* 从模版库中添加 */
    updateImport(cardItem) {
      let card = Object.assign(cardItem, { notNullFlow: [], stateCanEdit: null, authInfo: this.authInfo });
      this.additionalComponentList.push(card);
    },
    /** 
     * @description 保存数据
     * @param {object} otherParams 事件类型名称和颜色
     * @param {boolean} flag 是否返回上一页
     */
    async submit(flag) {
      try {
        const params = {
          eventTypeId: this.serviceEventTypeId,
          cardInfo: this.additionalComponentList,
          ...this.nameAndColor
        }

        const res = await SettingServiceEventApi.batchSaveEventCard(params)
        if (res.status === 0) {
          this.$platform.notification({
            title: this.$t('common.base.tip.saveSuccess'),
            type: 'success'
          });

          if (flag) {
            setTimeout(this.goBack, 1000);
          } else {
            // 重置初始数据
            this.flowData.initServiceEventTypeConfig = cloneDeep(this.serviceEventTypeConfig);
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
      } catch(err) {
        console.error(err);
      }      
    },
    goBack() {
      let fromId = window.frameElement.getAttribute('fromid');
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
      
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceStation,
        titleKey: '事件类型设置',
        reload: true,
        fromId
      })
    },
    async updateEventDataHandler() {
      this.cloneOldCard = cloneDeep(this.additionalComponentList);
      this.$emit('init');
    },
    /**更新附加组件数据*/
    updateEventCard() {
      try{
        // 查找当前添加的连接器附加组件
        const item = this.additionalComponentList.find(x => !this.cloneOldCard.some(v => v.id === x.id)) || {};
        if(Object.keys(item).length !== 0) {
          this.cloneOldCard.push(item);
        }
        this.additionalComponentList = this.cloneOldCard 
      }catch(error){
        console.log(error)
      }
    },
  },
  mounted() {
    this.fetchRoleList();
    this.fetchTemplateLibraryList();
  },
  components: {
    draggable,
    CardItem,
    AddCardDialog,
    EditRulesDialog,
    EditPremissDialog,
    PreviewCardDialog,
    NoDataViewNew
  },
};
</script>

<style lang="scss" scoped>
.card-setting-container {
  min-height: calc(100vh - 48px);
  overflow-y: auto;

  .card-setting-header {
    padding: 12px;
    background: #fff;

    .card-setting-title {
      display: flex;
      justify-content: space-between;

      h2 {
        margin: 0 16px 8px 0;
        font-size: $font-size-large;
      }

      button {
        .iconfont {
          margin-right: 8px;
        }
      }
    }

    .card-setting-msg {
      font-size: $font-size-small;
      color: $text-color-regular;
      line-height: 20px;

      .el-tooltip {
        font-size: $font-size-small;
        color: $text-color-secondary;
      }
    }
  }

  .card-setting-list {
    margin: 12px;

    .card-group {
      display: flex;
      flex-flow: wrap;
      min-height: 300px;
      width: calc(100% + 12px);

      .card-item {
        margin: 0 12px 12px 0;
      }
    }
  }
}
</style>
